import os,shutil
from django.forms.models import model_to_dict
from django.http.response import HttpResponse, JsonResponse
from website_server.models import CommentsTopicsTab, ReportCommentsTab, ReportTopicsTab, TopicsTab, UserinfoTab
from website_server.utils import getID,getTime, http_post,model_to_list,log_in
from website_server.views import SystemInformsClass

# Create your views here.
# 发布话题
@log_in
def uploadTopics(request):
  try:
    rq = request.POST
    if rq.get('title') == '':
      raise Exception
    file = request.FILES
    fileUrl = list()
    topics = TopicsTab()
    topics.topicsid = getID()
    topics.username = UserinfoTab.objects.get(username=request.session['user'])
    topics.time = getTime()
    topics.title = rq.get('title')
    topics.content = rq.get('content')
    topics.filetype = rq.get('fileType')
    topics.visit = 0
    path = 'static/topics/' + topics.topicsid
    # 文件存储
    if file:
      os.makedirs(path)
      myFile = None
      for i in file:
        myFile = file[i]
        if myFile:
          fileName = topics.topicsid + i + '.' + myFile.name.split('.')[-1]
          filePath =  path + '/' + fileName
          with open(filePath, 'wb') as f:
            for s in myFile.chunks():
              f.write(s)
          fileUrl.append('/' + filePath)
    topics.fileurl = ','.join(fileUrl)
    topics.save()
    return HttpResponse(1)
  except Exception as err:
    print(err)
    return HttpResponse(0)

# 获取用户话题内容
@http_post
def getUserTopics(request):
  try:
    rq = request.POST
    username = rq.get('userName',False) or request.session.get('user')
    topics = TopicsTab.objects.filter(username=username).order_by('-time')
    result = [{
      **model_to_dict(x),
      'commentCount': CommentsTopicsTab.objects.filter(topicsid=x.topicsid).count()
    } for x in topics]
    return JsonResponse({'data': result})
  except Exception:
    return HttpResponse(0)

# 删除话题
@log_in
def removeTopics(request):
  try:
    rq = request.POST
    id = rq.get('id')
    topics = TopicsTab.objects.get(topicsid=id)
    topics.delete()
    path = 'static/topics/' + id
    if os.path.isdir(path):
      shutil.rmtree(path)
      os.mkdir(path)
      os.rmdir(path)
    return HttpResponse(1)
  except Exception as err: 
    return HttpResponse(err)

# 获取全部话题数据
@http_post
def getTopics(request):
  topics = TopicsTab.objects.all().order_by('-time')
  result =[{
    **model_to_dict(x.username),
    **model_to_dict(x),
    'commentCount': CommentsTopicsTab.objects.filter(topicsid=x.topicsid).count(),
    } for x in topics]
  return JsonResponse({'data': result})

# 获取单个话题数据
@http_post
def getTopic(request):
  rq = request.POST
  if rq.get('id') != None:
    topic = TopicsTab.objects.get(topicsid=rq.get('id'))
    topic.visit += 1
    topic.save()
    result = {**model_to_dict(topic)}
    topics = TopicsTab.objects.filter(username=result.get('username')).order_by('-time')[0:10]
    return JsonResponse({'result':result,'topics': model_to_list(topics)})
  else:
    return HttpResponse('请稍后重试')

# 发表评论
@log_in
def uploadComments(request):
  rq = request.POST
  if rq.get('content') != None and rq.get('topicsid') != None:
    CommentsTopics = CommentsTopicsTab()
    CommentsTopics.commentid = getID()
    CommentsTopics.topicsid = TopicsTab.objects.get(topicsid=rq.get('topicsid'))
    CommentsTopics.username = UserinfoTab.objects.get(username=request.session.get('user'))
    CommentsTopics.content = rq.get('content')
    CommentsTopics.time = getTime()
    CommentsTopics.save()
    return HttpResponse(1)
  else:
    return HttpResponse('请稍后重试!')

# 获取评论
@http_post
def getComments(request):
  rq = request.POST
  if rq.get('topicsid') != None:
    CommentsTopics = CommentsTopicsTab.objects.filter(topicsid=TopicsTab.objects.get(topicsid=rq.get('topicsid'))).order_by('-time')
    CommentsTopics = [{
      **model_to_dict(x),
      'name': x.username.name,
      'picture': x.username.picture
    } for x in CommentsTopics]
    return JsonResponse({'data':CommentsTopics})
  else:
    return HttpResponse('系统繁忙')

# 删除评论
@log_in
def removeComment(request):
  rq = request.POST
  id = rq.get('id')
  if id :
    comment = CommentsTopicsTab.objects.filter(commentid=id).first()
    if comment:
      SystemInformsClass(username=comment.username,obj=comment).create(105)
      comment.delete()
      return HttpResponse(1)
    else:
      return HttpResponse('评论不存在')
  else:
    return HttpResponse('参数错误')

# 举报话题或评论
@log_in
def submitReport(request):
  try:
    rq = request.POST
    id = rq.get('id')
    type = rq.get('type')
    username = request.session.get('user')
    if type == '话题':
      if ReportTopicsTab.objects.filter(username=username,topicsid=id).first():
        raise Exception('请勿重复举报!')
      report = ReportTopicsTab.objects.create(
        reportid = getID(),
        username = UserinfoTab.objects.get(username=username),
        time = getTime(),
        topicsid = TopicsTab.objects.filter(topicsid=id).first(),
        cause = rq.get('cause')
      )
      return JsonResponse(model_to_dict(report))
    elif type == '评论':
      if ReportCommentsTab.objects.filter(username=username,commentid=id).first():
        raise Exception('请勿重复举报!')
      report = ReportCommentsTab.objects.create(
        reportid = getID(),
        username = UserinfoTab.objects.get(username=username),
        time =getTime(),
        commentid = CommentsTopicsTab.objects.filter(commentid=id).first(),
        cause = rq.get('cause')
      )
      return JsonResponse(model_to_dict(report))
    else:
      return HttpResponse('参数错误')
  except Exception as err:
    return HttpResponse(err)